Using modelflow with World Bank models
Contents
1. Using modelflow with World Bank models¶
The Modelflow python package has been developed to solve a wide range of models, see the modelflow github web site for working examples of the Solow Model, the FR/USB model and others.
The package has been substantially expanded to include special features that enable it to work with World Bank models originally developed in EViews and designed to use EViews Model Object for simuation.
This chapter illustrates how to access these models, how to load them into a modelflow anaconda environment on your computer and how to perform a variety of simulations
1.1. Accessing a world bank model¶
At this time several World bank macrostructural models are available to download and use with modelflow. These include a macrostructural model for:
Indonesia
Nepal
Croatia
Iraq
Kenya
Bolivia
Each of these models has been developed as part of the outreach work of the World Bank. The basic modelling framework of each of these models is outlined in Burns et al. [2019] with specific extensions reflecting features of the individual country modelled.
This book uses as an example a climate aware model for Pakistan developed in 2020 and described in Burns et al. [2021] .
The World Bank models are distributed in the pcim file format of the modelflow and can be downloaded by right clicking on the links above. The Pakistan model can be downloaded here by right clicking on the above link and selecting Save Link as and placing the file on a directory accessible by your modelflow installation.
from worldbankMFModModels import pak
1.2. Preparing your python environment¶
As always, the modelflow and other python packages that will be used need to be imported into your python session. The examples here and this book were written and solved in a Jupyter Notebook. There are some Jupyter specific commands included in these examples and these are annotated. However, the bulk of the content of the programs can be run in other environments, including Interactive Development Environments (IDE) like Spyderor MS Visual Code. All the programs have been tested under spyder as well as Jupyter Notebook.
It is assumed that:
you have already installed
modelflowand its various support packages following the instructions in Chapter xxyou are using Anaconda, and that
you have activated your
modelflowenvironment by executing the following command from your python command line:
conda activate modelflow
where modelflow is the name you have given to the conda environment into which you installed modelflow.
# import the model class from modelflow package
from modelclass import model
import modelmf # Add useful features to pandas dataframes
# using utlities initially developed for modelflow
model.widescreen() # These modelflow commands ensure that outputs from modelflow play well with Jupyter Notebook
model.scroll_off()
%load_ext autoreload
%autoreload 2
1.3. Working with PakMod under modelflow¶
The basic method for working with any model is the same. Indeed the initial steps followed here are the same as were followed during the simple model discussion.
Process:
Prepare the workspace
Load the model Modelflow
Design some scenarios
Simulate the model
Visualize the results
1.3.1. Load a pre-existing model, data and descriptions¶
To load a model use the model.modelload() method of modelflow.
The command below
mpak,bline = model.modelload('C:\mflow\modelflow-manual\papers\mfbook\content\models\pak.pcim', alfa=0.7,run=1,keep= 'Baseline')
instantiates (creates an instance of) a modelflow model object and assigns it to the variable name mpak. The run=1 option executes the model and assigns the result of the model execution to the dataframe bline. The model is solved with the parameter alfa set to 0.7. The \(alfa \in (0,1)\) parameter determines the step size of the solution engine. The larger alfa the larger the step size. Larger step sizes solve faster, but may have trouble finding a unique solution. Smaller step sizes take longer to solve but are more likely to find a unique solution. Values of alfa=.7 work well for World Bank models.
The keep option instructs modelflow to maintain in the model object (mpak) the results of the intitial scenario, assigning it the text name Baseline.
#Replace the path below with the location of the pak.pcim file on your computer
mpak,bline = model.modelload('C:\mflow\modelflow-manual\papers\mfbook\content\models\pak.pcim', \
alfa=0.7,run=1,keep= 'Baseline')
file read: C:\mflow\modelflow-manual\papers\mfbook\content\models\pak.pcim
Note
the variable bline contains the dataframe with the results of the simulation. This is distinct from the data that is stored by the kept= command. That said, the data associated with each, while stored separately, have the same numerical values. The keep option is described in more detail toward the end of this section.
Box [^BoxWBMnemonics]: World Bank Mnemonics
A typical World Bank model will have in excess of 300 variables. Each has a mnemonic that is structured in a specific way, The root for almost all are 14 characters long (some special variables have additional characters appended to this root) (see discussion in section).
where:
Letters |
Meaning |
|---|---|
\(\color{green}{\texttt{CCC}}\) |
The three-leter ISO code for a country – i.e. IDN for Indonesia, RUS for Russia |
\(\color{red}{\texttt{AA}}\) |
The two-letter major accounting system to which the variable attaches, |
\(\color{lime}{\texttt{MMM}}\) |
The three-letter major sub-category of the data - i.e. GDP, EXP - expenditure |
\(\color{blue}{\texttt{NNNN}}\) |
The four-letter minor sub-category MKTP for market prices |
\(\color{magenta}{\texttt{U}}\) |
The measure (K: real variable;C: Current Values; X: Prices) |
\(\color{black}{\texttt{C}}\) |
denotes the Currency (N: National currency; D: USD; P: PPP) |
Common major accounting systems mnemonics: the, \(\color{red}{\texttt{AA}}\)s from above:
Code |
Meaning |
|---|---|
NY |
National income |
NE |
National expenditure Accounts |
NV |
Value added accounts |
GG |
General Government Accounts |
BX |
Balance of Payments: Exports |
BM |
Balance of Payments: Imports |
BN |
Balance of Payments: Net |
BF |
Balance of Payments: Financial Account |
Thus
Mnemonic |
Meaning |
|---|---|
IDNNYGDPMKTPKN |
Indonesia GDP at market prices, real in Indonesian Rupiah |
KENNECPNPRVTXN |
Kenya Private (household) consumption expenditure schillings deflator |
BOLGGEXPGNFSCN |
Bolivia Government Expenditure on Goods and services (GNFS) in current Bolivars |
HRVGGREVDCITCN |
Croatia Government Revenues Direct Corporate Income Taxes in current Euros |
NPLBXGSRNFSVCD |
Nepal BOP Exports of non-factor services (goods and services) in current USD |
1.3.2. Extracting information about the model¶
The newly loaded python object mpak is an instance of the model class and as such inherits the methods (functions) and properties (data) of that class. To learn about the model there are a variety of information methods that can be used to extract information about the model and its data.
Information about a specific
Method |
Example |
Information returned |
|---|---|---|
|
|
Dictionary of mnemonics and their variable descriptions |
|
|
List of variable description alone |
Note
Wildcards
The * character in the command mpak['PAKNECON*XN'].names is a wildcard character and the extopression will return all variables that begin PAKNECON and end XN. the ? is another wildcard expression. It will match only single characters. Thus mpak['PAKNECONPRVT?N'].names would return three variables: PAKNECONPRVTKN, PAKNECONPRVTXN, and PAKNECONPRVTXN. The real, current value, and deflators for household consumption expenditure.
Information about a number of variables that meet certain search criteria
The above functions can be used in conjunction with a wildcard specification to extract the same information about a number of variables that meet the criteria. To extract a list of all variables matching a pattern, we can use same methods.
Wildcards
The * operator matches multiple characters, the ? operator matches just one character
Method |
Example |
Information returned |
|---|---|---|
|
|
Returns Dictionary of all mnemonic and variable descriptions whose mnemonic matches |
|
|
Returns list of variable descriptions whose mnemonic matches |
|
|
Returns list of variable mnemonics that match |
The ! operator If a wildcard is preceded by an exclamation mark ! the search will be done over the description of variables instead of the mnemonic
Method |
Example |
Information returned |
|---|---|---|
|
|
Returns Dictionary of all mnemonic and variable descriptions whose description contains the string GDP |
|
|
Returns list of variable descriptions whose description contains the string Consumption |
|
|
Returns list of variable mnemonics whose description contains the string Agriculture |
#Operator The # operator passes a predefined list to the search function and returns variable info about the variables in the list
Method |
Example |
Information returned |
|---|---|---|
|
|
Returns Dictionary of all mnemonic and variable descriptions of the variables contained in the list MyList |
|
|
Returns list of variable descriptions of variables contained in the list MyList |
|
|
Returns list of variable mnemonics of variables contained in the list MyList |
1.3.2.1. Some examples¶
Return all variables that begin PAKNECON and end KN.
mpak['PAKNECON*XN'].names
['PAKNECONENGYXN', 'PAKNECONGOVTXN', 'PAKNECONOTHRXN', 'PAKNECONPRVTXN']
Return a dictionary comprised of the mnemonics and the descriptions of all the variables that begin PAKNECONPRVT and end N, but have one character between the T and the N.
mpak['PAKNECONPRVT?N'].des
PAKNECONPRVTCN : Pvt. Cons., LCU mn
PAKNECONPRVTKN : HH. Cons Real
PAKNECONPRVTXN : Implicit LCU defl., Pvt. Cons., 2000 = 1
Return a list of the full description all the variables that have the word GDP in their description.
mpak['!*GDP*'].des
PAKBNCABFUNDCD_ : Current Account Balance (% of GDP)
PAKGDPPCKD : GDP per capita, 2000 US$ mn
PAKGDPPCKN : GDP per capita, 2005 LCU mn
PAKNYGDPDISCCN : GDP Disc., LCU mn
PAKNYGDPDISCKN : GDP Disc., 2000 LCU mn
PAKNYGDPFCSTKN : GDP Factor Cost Local Currency units Volumes National base year
PAKNYGDPFCSTXN : GDP Factor Cost Local Currency units Implicit Price deflator
PAKNYGDPFCSTXN_A : Add factor:GDP Factor Cost Local Currency units Implicit Price deflator
PAKNYGDPFCSTXN_D : Fix dummy:GDP Factor Cost Local Currency units Implicit Price deflator
PAKNYGDPFCSTXN_FITTED : Fitted value:GDP Factor Cost Local Currency units Implicit Price deflator
PAKNYGDPFCSTXN_X : Fix value:GDP Factor Cost Local Currency units Implicit Price deflator
PAKNYGDPGAP_ : Output Gap (% of Potential GDP)
PAKNYGDPMKTPCD : GDP, Market Prices, US$ mn
PAKNYGDPMKTPCN : GDP, Market Prices, LCU mn
PAKNYGDPMKTPKD : GDP, Market Prices, 2000 US$ mn
PAKNYGDPMKTPKN : Real GDP
PAKNYGDPMKTPXN : GDP, Marker Prices, LCU Price defl., 2000 = 1
Return a dictionary comprised of the variable name and description if all variables in a list.
#Why does this not work?
mylist=['PAKNECONPRVTKN','PAKNECONGOVTKN','PAKNEGDIFTOTKN','PAKNEEXPGNGSKN','PAKNEIMPGNFSKN']
mpak['#mylist'].des
No grouping like this. Select from:
Headline
National income accounts
National expenditure accounts
Value added accounts
Balance of payments exports
Balance of payments exports and value added
Balance of Payments Financial Account
General government fiscal accounts
World all
PAK all
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
Input In [6], in <cell line: 3>()
1 #Why does this not work?
2 mylist=['PAKNECONPRVTKN','PAKNECONGOVTKN','PAKNEGDIFTOTKN','PAKNEEXPGNGSKN','PAKNEIMPGNFSKN']
----> 3 mpak['#mylist'].des
File ~\.conda\envs\modelflow\lib\site-packages\ModelFlow-1.0.8-py3.9.egg\modelclass.py:1260, in Org_model_Mixin.__getitem__(self, name)
1252 def __getitem__(self, name):
1253 '''
1254 To execute the index operator []
1255
1256 Uses the :any:`modelvis.vis` operator
1257
1258 '''
-> 1260 a = self.vis(name)
1262 return a
File ~\.conda\envs\modelflow\lib\site-packages\ModelFlow-1.0.8-py3.9.egg\modelclass.py:3735, in Display_Mixin.vis(self, *args, **kwargs)
3733 if not hasattr(self, '_vis'):
3734 self._vis = mv.vis
-> 3735 return self._vis(self, *args, **kwargs)
File ~\.conda\envs\modelflow\lib\site-packages\ModelFlow-1.0.8-py3.9.egg\modelvis.py:50, in vis.__init__(self, model, pat, names, df)
48 self.__pat__ = pat
49 if type(names) == type(None):
---> 50 self.names = self.model.vlist(self.__pat__)
51 else:
52 self.names = names
File ~\.conda\envs\modelflow\lib\site-packages\ModelFlow-1.0.8-py3.9.egg\modelclass.py:1107, in Org_model_Mixin.vlist(self, pat)
1105 lf='\n'
1106 print(f'No grouping like this. Select from: {lf}{lf.join(self.var_groups.keys())}')
-> 1107 raise Exception('Try with a correct group name')
1109 ipat = upat
1110 # breakpoint()
Exception: Try with a correct group name
the method .var_description returns the descriptor of the associated variable. This method does not accept wildcards.
mpak.var_description['PAKNYGDPMKTPKN']
'*NYGDPMKTP?N'
1.3.2.2. Equation information methods¶
There are two functions to extract the equations from a model.
Command |
Effect |
|---|---|
|
Returns a normalized version of the equation (the one actually used in modelflow) |
|
In models imported from Eviews, reports the original eviews specification |
The equation for consumption in mpak we see that it follows something very close to this formulation.
mpak.PAKNECONPRVTKN.frml
Endogeneous: PAKNECONPRVTKN: HH. Cons Real
Formular: FRML <DAMP,STOC> PAKNECONPRVTKN = (PAKNECONPRVTKN(-1)*EXP(PAKNECONPRVTKN_A+ (-0.2*(LOG(PAKNECONPRVTKN(-1))-LOG(1.21203101101442)-LOG((((PAKBXFSTREMTCD(-1)-PAKBMFSTREMTCD(-1))*PAKPANUSATLS(-1))+PAKGGEXPTRNSCN(-1)+PAKNYYWBTOTLCN(-1)*(1-PAKGGREVDRCTXN(-1)/100))/PAKNECONPRVTXN(-1)))+0.763938860758873*((LOG((((PAKBXFSTREMTCD-PAKBMFSTREMTCD)*PAKPANUSATLS)+PAKGGEXPTRNSCN+PAKNYYWBTOTLCN*(1-PAKGGREVDRCTXN/100))/PAKNECONPRVTXN))-(LOG((((PAKBXFSTREMTCD(-1)-PAKBMFSTREMTCD(-1))*PAKPANUSATLS(-1))+PAKGGEXPTRNSCN(-1)+PAKNYYWBTOTLCN(-1)*(1-PAKGGREVDRCTXN(-1)/100))/PAKNECONPRVTXN(-1))))-0.0634474791568939*DURING_2009-0.3*(PAKFMLBLPOLYXN/100-((LOG(PAKNECONPRVTXN))-(LOG(PAKNECONPRVTXN(-1)))))) )) * (1-PAKNECONPRVTKN_D)+ PAKNECONPRVTKN_X*PAKNECONPRVTKN_D $
PAKNECONPRVTKN : HH. Cons Real
DURING_2009 :
PAKBMFSTREMTCD : Imp., Remittances (BOP), US$ mn
PAKBXFSTREMTCD : Exp., Remittances (BOP), US$ mn
PAKFMLBLPOLYXN : Key Policy Interest Rate
PAKGGEXPTRNSCN : Current Transfers
PAKGGREVDRCTXN : Direct Revenue Tax Rate
PAKNECONPRVTKN_A: Add factor:HH. Cons Real
PAKNECONPRVTKN_D: Fix dummy:HH. Cons Real
PAKNECONPRVTKN_X: Fix value:HH. Cons Real
PAKNECONPRVTXN : Implicit LCU defl., Pvt. Cons., 2000 = 1
PAKNYYWBTOTLCN : Total Wage Bill
PAKPANUSATLS : Exchange rate LCU / US$ - Pakistan
The mpak['PAKNECONPRVTKN'].eviews command returns the equations before they were normalized. In most cases this is a slightly more legible form. Here following the EViews syntax, \(\Delta ln()\) is written as dlog().
mpak.PAKNECONPRVTKN.eviews
DLOG(PAKNECONPRVTKN) =- 0.2*(LOG(PAKNECONPRVTKN( - 1)) - LOG(1.21203101101442) - LOG((((PAKBXFSTREMTCD( - 1) - PAKBMFSTREMTCD( - 1))*PAKPANUSATLS( - 1)) + PAKGGEXPTRNSCN( - 1) + PAKNYYWBTOTLCN( - 1)*(1 - PAKGGREVDRCTXN( - 1)/100))/PAKNECONPRVTXN( - 1))) + 0.763938860758873*DLOG((((PAKBXFSTREMTCD - PAKBMFSTREMTCD)*PAKPANUSATLS) + PAKGGEXPTRNSCN + PAKNYYWBTOTLCN*(1 - PAKGGREVDRCTXN/100))/PAKNECONPRVTXN) - 0.0634474791568939*@DURING("2009") - 0.3*(PAKFMLBLPOLYXN/100 - DLOG(PAKNECONPRVTXN))
1.4. Behavioural equations in the MFMod framework¶
Recall a behavioural equation determines the value of an endogenous variable. For many of the variables in Wold Bank models, behavioural functions are estimated using an Error Correction Framework that splits the equation into a theoretically determined long run component and a more idiosyncratic short-run component.
Looking at the eviews representation of the consumption function:
DLOG(PAKNECONPRVTKN) =- 0.2*(LOG(PAKNECONPRVTKN( - 1)) - LOG(1.21203101101442) - LOG((((PAKBXFSTREMTCD( - 1) - PAKBMFSTREMTCD( - 1))*PAKPANUSATLS( - 1)) + PAKGGEXPTRNSCN( - 1) + PAKNYYWBTOTLCN( - 1)*(1 - PAKGGREVDRCTXN( - 1)/100))/PAKNECONPRVTXN( - 1))) + 0.763938860758873*DLOG((((PAKBXFSTREMTCD - PAKBMFSTREMTCD)*PAKPANUSATLS) + PAKGGEXPTRNSCN + PAKNYYWBTOTLCN*(1 - PAKGGREVDRCTXN/100))/PAKNECONPRVTXN) - 0.0634474791568939*@DURING("2009") - 0.3*(PAKFMLBLPOLYXN/100 - DLOG(PAKNECONPRVTXN))
Below the mnemonics are simplified to ease reading of the equation using:
Model Mnemonic |
Simplified |
Meaning |
|---|---|---|
PAKNECONPRVTKN |
\(CON^{KN}_t\) |
Household Consumption |
(PAKBXFSTREMTCD - PAKBMFSTREMTCD)*PAKPANUSATLS |
\(Remit^{net}_t\) |
Net remittances inflows in LCU |
PAKGGEXPTRNSCN |
\(TRANSF^{hhld}_t\) |
Government transfers to households |
DURING_2010 |
\(D^{2010}_t\) |
A dummy |
PAKFMLBLPOLYXN |
\(r^{policy}_t\) |
Policy Rate |
PAKGGREVDRCTXN |
\(DirectTxR_t\) |
Direct Taxes: Effective rate |
PAKNECONPRVTKN_A |
\(CON^{KN_AF}_t\) |
Add factor:Household Consumption |
PAKNECONPRVTXN |
\(CON^{XN}_t\) |
Household Consumption Deflator |
PAKNYYWBTOTLCN |
\(WAGEBILL^{CN}_t\) |
Economy-wide wage bill |
Where in this instance the short-run elasticity of consumption to disposable income is .76 , and the short run elasticity of consumption to the real interest rate is 0.3.
1.4.1. The ECM specification¶
Pretty sure this repeats and earlier section. Delete one
The ECM approach used in World Bank models is described in [Wickens and Breusch, 1988], and addresses the above challenge by modelling both the long run relationship and the short run short run behaviour and brings them together into one equation.
The ECM specification is therefore a single equation comprised of two parts (the long run relationship, and the short-run relationship).
Consider as an example two variables say consumption and disposable income. Both have an underlying trend or in the parlance are co-integrated to degree 1. For simplicity we call them y an x.
1.4.1.1. The short run relationship¶
In its simplest form we might have a short run relationship between the growth rates of our two variables such that:
or substituting lower case letters for the logged values.
1.4.1.2. The long run equation¶
The long run relates the level of the two (or more) variables. We can write a simple version of that equation as:
Rewriting this (in logarithms) it can be expressed as:
1.4.2. The long run equation in the steady state¶
First we note that in the steady state the expected value of the error term in the long run equation is zero (\(\eta_t=0 \)) so in those conditions we can simplify the long run relationship to:
or equivalently (substituting A for the log of \(\alpha\)).
Moreover if we multiplied this by some arbitrary constant say \(-\lambda\) it would still equal zero.
and in the steady state this will also be true for the lagged variables
1.5. Putting it together¶
From before we have the short run equation:
Inserting the steady state expression into the short run equation makes no difference (in the long run) because in the long run it is equal to zero.
When the model is not in the steady state the expression \(y_{t-1}-A-βx_{t-1}\) is of course the error term from the long run equation (a measure of how far the dependent variable is from equilibrium).
1.5.1. Lambda, the speed of adjustment¶
The parameter \(\lambda\) can be interpreted as the speed of adjustment. As long as \(\lambda\) is greater than zero and less or equal to one if there are no further disturbances ( \(\epsilon_t=0\)) the expression multiplied by lambda will slowly decline toward zero. How fast depends on how large or small is \(\lambda\).
To be convergent \(\lambda\) must be between 0 and 2, if its is negative or greater than one, then the long run portion of the equation will cause the disequilibrium to grow each period (\(\lambda\) >1) not diminish or if (\(\lambda\) >1<2) output will oscillate from positive to negative (\(\lambda <0\)).
Intuitively, the long run error term measures how far we are from equilibrium one period earlier (at t-1). The ECM term ensures that we will slowly converge to equilibrium – the point at which the long run equation holds exactly. If $\(\lambda\)\( is greater than zero but less than one (or equal to one) some portion of the previous period year's disequilibrium will be absorbed each year. How much is absorbed depends on the size of estimated speed of the adjustment coefficient \)\lambda$.
Looking at an ECM equation we can then break it up into its component parts. For the consumption function it will look something like this: